package com.mes.inventory.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.mes.common.dao.BasicDao;
import com.mes.inventory.dao.iface.IWarehouseDao;
import com.mes.inventory.dao.iface.IWarehouseKeeperDao;
import com.mes.inventory.domain.Warehouse;
import com.mes.inventory.domain.WarehouseKeeper;

@Repository
public class WarehouseDao extends BasicDao<Warehouse> implements IWarehouseDao{	
	
	@Autowired
	IWarehouseKeeperDao warehouseKeeperDao;
	
	/**
	 * 获取授权给某个库管员的库房列表
	 * @param employeeUid 库管员唯一号
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Warehouse> getWarehousesByEmployeeUid(String employeeUid) throws Exception {
		List<Warehouse> list = null;

		Session session = this.getSessionFactory().getCurrentSession();
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(WarehouseKeeper.class);
			crit.add(Restrictions.eq("employeeUid", employeeUid));
			List<WarehouseKeeper> keepers = warehouseKeeperDao.query(crit, null);
			if(keepers != null && keepers.size() > 0){
				list = new ArrayList<Warehouse>();
				for(WarehouseKeeper keeper : keepers){
					list.add(keeper.getWarehouse());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

		return list;
	}
	
	
	@Override
	public List<Warehouse> getWarehouseByDeptUid(String deptUid) throws Exception{
		List<Warehouse> list = null;
		try {
			DetachedCriteria crit = DetachedCriteria.forClass(Warehouse.class);
			crit.add(Restrictions.like("deptUid", deptUid, MatchMode.START));
			crit.addOrder(Property.forName("warehouseName").asc());

			list = this.query(crit, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return list;
	}
	
	

}
